package br.com.abril.prevision;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import br.com.abril.wallet.PrevisionWalletRepository;

@Service
public class PrevisionService {

	@Autowired
	private PrevisionRepository repository;
	
	@Autowired
	private ExecutivePrevisionService executivePrevisionService;
	
	@Autowired
	private PrevisionWalletRepository previonWallets;
	
	public PrevisionRepository allPrevision() {
		return repository;
	}
	
	@Transactional
	public void save (List<Prevision> previsions) {
		repository.save(previsions);
	}
	
	@Transactional
	public void deleteAll() {
		repository.deleteAllInBatch();
		executivePrevisionService.allPrevisions().deleteAllInBatch();
	}

	
	public PrevisionWalletRepository allWallets() {
		return previonWallets;
	}
	
	public ExecutivePrevisionService getExecutivePrevisionService() {
		return executivePrevisionService;
	}
	
	
	public List<ExecutivePrevision> filterTeamByLastPrevison(String lastPrevision , List<ExecutivePrevision> executives) {
		return indexExecutivesForPrevision(executives).get(lastPrevision);
	}
	
	public Map<String, List<ExecutivePrevision>> indexExecutivesForPrevision (List<ExecutivePrevision> executives) {
		
		Map<String, List<ExecutivePrevision>> indexed = new HashMap<String, List<ExecutivePrevision>>();
		
		for ( ExecutivePrevision executive : executives ) {
			if ( !indexed.containsKey(executive.getPrevisao__c()) ) {
				indexed.put(executive.getPrevisao__c(), new ArrayList<ExecutivePrevision>() );
			}
			
			indexed.get(executive.getPrevisao__c()).add(executive);
			
		}
		
		return indexed;
		
	}	
	
	@Transactional(propagation=Propagation.REQUIRES_NEW)
	public void updateExecutivePrevisionsWithError ( List<ExecutivePrevision> executives , Exception exception ) {
		for (ExecutivePrevision executive : executives) {
			executive.setJobExecutionStatus( "UPLOADING_ERROR" );
			executive.setJobExecutionExceptionInfo( exception.getMessage() );
		}
		executivePrevisionService.save(executives);
	}	
	

	
}
